"""处理账户注册登录"""
import uuid
import datetime
from django.shortcuts import render, HttpResponse,redirect
from django.http import JsonResponse
from django_redis import get_redis_connection
from web.forms import account
from web import models


def register(request):
    if request.method == 'GET':
        form = account.RegisterModelForm()
        return render(request, "register.html", {'form': form})

    form = account.RegisterModelForm(data=request.POST)

    if form.is_valid():
        # 验证通过，写入数据库，密码记得加密,并返回添加的对象
        instance = form.save()

        # 创建交易记录
        price_policy = models.PricePolicy.objects.filter(category=1).first()
        models.Transaction.objects.create(
            status=2,
            order=str(uuid.uuid4()),
            user=instance,
            price_policy=price_policy,
            count=0,
            price=0,
            create_datetime=datetime.datetime.now()
        )

        return JsonResponse({'status': True, 'data': '/login/sms/'})
    # 验证不通过，返回错误信息
    return JsonResponse({'status': False, 'errors': form.errors})


def send_sms(request):
    """发送短信"""
    form = account.SendSmsForm(request, data=request.GET)

    if form.is_valid():
        return JsonResponse({'status': True})
    return JsonResponse({'status': False, 'errors': form.errors})


def login_sms(request):
    """短信登录"""

    if request.method == 'GET':
        form = account.LoginSmsForm()
        return render(request, 'login_sms.html', {'form': form})

    form = account.LoginSmsForm(data=request.POST)
    if form.is_valid():
        mobile_phone = form.cleaned_data['mobile_phone']

        user_obj = models.UserInfo.objects.filter(mobile_phone=mobile_phone).first()

        request.session['user_id'] = user_obj.id
        request.session.set_expiry(60 * 60 * 24 * 14)
        # 校验成功返回
        return JsonResponse({'status': True, 'data': '/index/'})
    # 校验不成功返回
    return JsonResponse({'status': False, 'errors': form.errors})


def login(request):
    if request.method == 'GET':
        form = account.LoginForm(request)
        return render(request, 'login.html', {'form': form})

    form = account.LoginForm(request, request.POST)
    if form.is_valid():
        username = form.cleaned_data['username']
        password = form.cleaned_data['password']
        from django.db.models import Q
        user_obj = models.UserInfo.objects.filter(Q(mobile_phone=username) | Q(email=username)).filter(
            password=password).first()
        if user_obj:
            request.session['user_id'] = user_obj.id
            request.session.set_expiry(60 * 60 * 24 * 14)
            return redirect('index')
        else:
            form.add_error("username", "用户名或密码错误")
    return render(request, 'login.html', {'form': form})


def image_code(request):
    from untils.image_code import check_code
    image_object, code = check_code()

    request.session['code'] = code
    request.session.set_expiry(60)  # 主动修改session的过期时间为60s,默认为两周过期

    """图片写到内存中"""
    from io import BytesIO
    stream = BytesIO()
    image_object.save(stream, 'png')
    return HttpResponse(stream.getvalue())


def logout(request):
    request.session.flush()
    return redirect('index')
    # return render(request,'index.html')
